<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class StudentCourseLevelService
{
    // 列表
    public static function index($data)
    {
        // 参数校验与默认值设置
        $categoryId = isset($data['category_id']) && is_numeric($data['category_id']) ? (int)$data['category_id'] : 0;
        if ($categoryId <= 0) {
            return ['code' => 400, 'msg' => 'Invalid parameters', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }

        $limit = isset($data['limit']) && is_numeric($data['limit']) ? (int)$data['limit'] : 10;
        $limit = max(1, min(100, $limit)); // 限制每页数量在 1~100 之间

        try {
            // 分页查询
            $studio = \app\admin\model\StudentCourseLevel::where(['category_id' => $categoryId])
                ->field('level_id, level_name')
                ->order('level_id', 'desc')
                ->paginate($limit);

            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $studio];
        } catch (\Exception $e) {
            // 记录日志（此处省略日志记录）
            return ['code' => 500, 'msg' => 'Internal server error', 'state' => 'INTERNAL_ERROR', 'data' => null];
        }
    }


    // 保存
    public static function save($data)
{
    // 合并验证规则
    $validate = new Validate([
        'category_id' => 'require',
        'level_name' => 'require',
        'abbreviation' => 'require',
        'age_range' => 'require',
        'level_id' => 'optional', // 允许 level_id 存在但非必须
    ], [
        'category_id.require' => 'CategoryId is not empty',
        'level_name.require' => 'Level Name is not empty',
        'abbreviation.require' => 'Abbreviation is not empty',
        'age_range.require' => 'Age Range is not empty',
        'level_id.require' => 'LevelId is not empty',
    ]);

    if (!$validate->check($data)) {
        return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
    }

    // 显式开启事务
    Db::startTrans();
    try {
        if (isset($data['level_id']) && $data['level_id']) {
            // 单独验证 level_id 是否存在且合法（可选）
            if (!$validate->check(['level_id' => $data['level_id']])) {
                Db::rollback();
                return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
            }
            $result = \app\admin\model\StudentCourseLevel::update($data);
        } else {
            $result = \app\admin\model\StudentCourseLevel::create($data);
        }

        Db::commit();
    } catch (\Throwable $e) {
        Db::rollback();
        return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
    }

    return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
}


    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();
        // 验证$data['id']是否为空且为数字

        if (empty($data['level_id']) || !is_numeric($data['level_id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务删除数据
        try {
            $result = \app\admin\model\StudentCourseLevel::destroy($data['level_id']);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 下拉查询
    public static function select($data)
    {
        // 提取参数并验证
        $categoryId = $data['category_id'] ?? null;
        if (empty($categoryId) || !is_numeric($categoryId)) {
            return ['code' => 400, 'msg' => 'Invalid parameters', 'state' => 'INVALID_ARGUMENT', 'data' => null];
        }

        try {
            // 显式转换为整数，防止注入
            $categoryId = (int)$categoryId;

            // 查询数据
            $studio = \app\admin\model\StudentCourseLevel::where(['category_id' => $categoryId])
                ->field('level_id,level_name')
                ->order('level_id', 'desc')
                ->select();

            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $studio];
        } catch (\Exception $e) {
            // 记录异常日志（此处可根据项目实际接入日志系统）
            \think\facade\Log::error("StudentCourseLevel select error: " . $e->getMessage());

            return ['code' => 500, 'msg' => 'Internal server error', 'state' => 'SERVER_ERROR', 'data' => null];
        }
    }



}
